import React, {Component} from "react";
import {connect} from "react-redux";
import SearchBar from './SearchBar';
import SearchBox from './SearchBox';
import {SearchGamesContainer} from "./style";
import EventBus from "@/util/EventBus";
import _ from 'lodash';
import {HomeWrapper} from "@/component/Home/style";

class SearchGames extends Component {
    constructor(props) {
        super(props);
        this.handleBarChange = this.handleBarChange.bind(this);
        let query = this.props.location.query;
        this.state = {
            // 已选择的分类
            selectTypes: new Set(),
            selectPlatforms: new Set(),
            // 搜素的关键字
            searchValue: query && query.kw ? query.kw : null,
        }
    }

    componentDidMount() {
        EventBus.addListener('searchGames', (val) => {
            if (!_.isEmpty(val)) {
                this.setState({
                    kw: val
                })
            }
        })
    }

    componentWillUnmount() {
        EventBus.removeListener('searchGames', () => {
            console.log("已移除事件监听器：searchGames")
        })
    }

    handleBarChange({selectTypes = [], selectPlatforms = [], searchValue = ''}) {
        this.setState({
            selectTypes: [...selectTypes],
            selectPlatforms: [...selectPlatforms],
            searchValue
        })
    }

    render() {
        return <>
            <HomeWrapper>
                <SearchGamesContainer>
                    <SearchBar onChange={this.handleBarChange} key={'SearchBar'}/>
                    <SearchBox typeArray={this.state.selectTypes} platformArray={this.state.selectPlatforms}
                               keyword={this.state.searchValue} key={'SearchBox'}/>
                </SearchGamesContainer>
            </HomeWrapper>
        </>
    }
}

const mapStateToProps = (state) => {
    return {}
}
const mapDispatchToProps = (dispatch) => {
    return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchGames);
